// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  traceUser: true,
  env:'aaa111-9gh9fp5ieac4de5d'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    const _ = db.command
    const $ = db.command.aggregate

    var idlist = await db.collection('postReadHistory').aggregate()
    .group({
        _id: '$artId',
        count: $.sum(1),
    }).sort({
        count: -1,
    }).limit(9).end()
    console.log(idlist)
    //
    var result = []
    for (var i =0;i<idlist.list.length;i++){
        await db.collection('postinfo').where({
            _id: idlist.list[i]._id
        }).get().then(res => {
            result.push({
                title: res.data[0].desc,
                artId: res.data[0]._id,
                count: idlist.list[i].count,
                image: res.data[0].image[0]
                
            })
        })
    }
    return result
}